package org.mq.mymq.broker.netty.nameserver;

import com.alibaba.fastjson.JSON;
import org.mq.mymq.broker.cache.CommonCache;
import org.mq.mymq.common.coder.TcpMsg;
import org.mq.mymq.common.dto.HeartBeatDTO;
import org.mq.mymq.common.enums.NameServerEventCode;
import org.mq.mymq.common.enums.NameServerResponseCode;
import org.mq.mymq.common.remote.NameServerNettyRemoteClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName HeartBeatTask
 * @Description 心跳任务
 * @Author jiarong_ye
 * @Date 2025/6/19 19:09
 * @Version 1.0
 */
public class HeartBeatTaskManager {
    private static final Logger log = LoggerFactory.getLogger(HeartBeatTaskManager.class);
    private AtomicInteger heartBeatCounter = new AtomicInteger(0);
    /**
     * 开启心跳传输任务
     */
    public void startTask() {
        if (heartBeatCounter.getAndIncrement() > 0) {
            return;
        }
        Thread thread = new Thread(new HeartBeatRequestTask());
        thread.setName("heart-beart-request-task");
        thread.start();
    }

    private class HeartBeatRequestTask implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    TimeUnit.SECONDS.sleep(3);
                    NameServerNettyRemoteClient nameServerNettyRemoteClient = CommonCache.getNameServerClient().getNameServerNettyRemoteClient();
                    // 心跳包不需要额外透传过多参数，只需要告诉nameserver这个channel依然存活
                    HeartBeatDTO heartBeatDTO = new HeartBeatDTO();
                    heartBeatDTO.setMsgId(UUID.randomUUID().toString());
                    TcpMsg tcpMsg = new TcpMsg(NameServerEventCode.HEART_BEAT.getCode(), JSON.toJSONBytes(heartBeatDTO));
                    TcpMsg respMsg = nameServerNettyRemoteClient.sendSyncMsg(tcpMsg, heartBeatDTO.getMsgId());
                    if (NameServerResponseCode.HEART_BEAT_SUCCESS.getCode() != respMsg.getCode()) {
                        log.error("heart beat from nameserver is error:{}",respMsg.getCode());
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
